package ssm.blog.controller.admin;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import ssm.blog.entity.Album;
import ssm.blog.service.AlbumService;
import ssm.blog.util.ImageUtil;
import ssm.blog.util.ResponseUtil;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @program: lyon
 * @description: 相册控制层
 * @author: Lyon
 * @create: 2018-06-06 10:17
 **/
@Controller
@RequestMapping("/admin")
public class AdminAlbumsController {
    @Resource
    AlbumService albumService;
    @RequestMapping("/albumsAdd")
    String albumsAdd()
    {
        return "interface/admin/albumsAdd";
    }
    @RequestMapping("/albumEdit")
    String albumEdit(Integer id, Model model){
        Album album=albumService.getById(id);
        model.addAttribute("album",album);
        return "interface/admin/albumEdit";
    }
    @RequestMapping("/albumDele")
    String albumDele(Integer id,HttpServletResponse response,HttpSession session) throws Exception {
        int resultRows=albumService.deleByID(id,session);
        JSONObject result=new JSONObject();
        if(resultRows>0){
            result.put("success",true);
        }else{
            result.put("success",false);
        }
        ResponseUtil.write(response,result);
        return null;
    }
    @RequestMapping("/albumsDele")
    String albumsDele(HttpServletResponse response,String ids,HttpSession session)throws Exception{
        //分割得到所有ID
        String[] IDS_str=ids.split(",");
        //转化为Integer数组
        List<Integer> IDS_INT=new ArrayList<>();
        for(String i:IDS_str) {
            IDS_INT.add(Integer.valueOf(i));
        }
        //删除
        int resultRows=albumService.deles(IDS_INT,session);
        //返回删除结果
        JSONObject result=new JSONObject();
        if(resultRows>0){
            result.put("success",true);
        }else {
            result.put("success",false);
        }
        ResponseUtil.write(response,result);
        return null;
    }
    @RequestMapping("/updateAlbum")
    String updateAlbum(Album album,HttpServletResponse response) throws Exception {
        int resultRows=albumService.update(album);
        JSONObject result=new JSONObject();
        if(resultRows>0){
            result.put("success",true);
        }else{
            result.put("success",false);
        }
        ResponseUtil.write(response,result);
        return null;
    }
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    String uploadImg(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        // TODO Auto-generated method stub
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                long site=0;
                if(file != null){
                    site++;
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        //重命名上传后的文件名  按照年月日时分秒进行命名
                        try {
                            File fullimageFolder = new File(session.getServletContext().getRealPath("/static/images/albums/fulls"));
                            if(!fullimageFolder.exists()){
                                fullimageFolder.mkdirs();
                            }
                            File thumbsimageFolder=new File(session.getServletContext().getRealPath("/static/images/albums/thumbs"));
                            if(!thumbsimageFolder.exists()){
                                thumbsimageFolder.mkdirs();
                            }
                            long id=System.currentTimeMillis()-site*1000000000;
                            File fullfile = new File(fullimageFolder,id+".jpg");
                            File thumbsfile=new File(thumbsimageFolder,id+".jpg");
                            file.transferTo(fullfile);
                            ImageIO.write(ImageUtil.change2jpg(fullfile),"jpg",fullfile);
                            ImageUtil.resizeImage(fullfile,0.3,thumbsfile);
                            Album album=new Album();
                            album.setFull(fullfile.getName());
                            album.setThumb(thumbsfile.getName());
                            int resultRows=albumService.add(album);
                            JSONObject result=new JSONObject();
                            if(resultRows>0){
                                result.put("success",true);
                            }else{
                                result.put("success",false);
                            }
                            ResponseUtil.write(response,result);
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }

        }
        return null;
    }
}
